<template>
  <div class="map-container">
    <el-button class="back" size="small" @click="handleBack">上一级</el-button>
    <div id="chart-panel" class="map"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'SalesMap',
  data() {
    return {
      myChart: null,
      geoJson: {},
      parentInfo: [{ cityName: '全国', code: 100000 }],
    };
  },
  mounted() {
    this.init(100000);
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
  },
  methods: {
    init(adcode) {
      this.getGeoJson(adcode).then((data) => {
        this.geoJson = data;
        this.getMapData();
      });
    },
    getGeoJson(adcode, childAdcode = '') {
      return new Promise((resolve, reject) => {
        function insideFun(adcode, childAdcode) {
          AMapUI.loadUI(['geo/DistrictExplorer'], (DistrictExplorer) => {
            const districtExplorer = new DistrictExplorer();
            districtExplorer.loadAreaNode(adcode, (error, areaNode) => {
              if (error) {
                console.error(error);
                reject(error);
                return;
              }
              let Json = areaNode.getSubFeatures();
              if (Json.length === 0) {
                const parent = areaNode._data.geoData.parent.properties.acroutes;
                insideFun(parent[parent.length - 1], adcode);
                return;
              }

              if (childAdcode) {
                Json = Json.filter((item) => item.properties.adcode == childAdcode);
              }
              const mapJson = { features: Json };
              resolve(mapJson);
            });
          });
        }
        insideFun(adcode, childAdcode);
      });
    },
    getMapData() {
      let mapData = [],
          pointData = [],
          sum = 0;

      this.geoJson.features.forEach((item) => {
        const value = Math.random() * 3000;
        mapData.push({
          name: item.properties.name,
          value: value,
          cityCode: item.properties.adcode,
        });
        pointData.push({
          name: item.properties.name,
          value: [item.properties.center[0], item.properties.center[1], value],
          cityCode: item.properties.adcode,
        });
        sum += value;
      });

      mapData = mapData.sort((a, b) => b.value - a.value);
      this.initEchartMap(mapData, sum, pointData);
    },
    initEchartMap(mapData, sum, pointData) {
      const xData = [],
          yData = [];
      let min = mapData[mapData.length - 1].value;
      let max = mapData[0].value;

      if (mapData.length === 1) min = 0;

      mapData.forEach((c) => {
        xData.unshift(c.name);
        yData.unshift(c.value);
      });

      echarts.registerMap(this.parentInfo.length === 1 ? 'china' : 'map', this.geoJson);

      const option = {
        backgroundColor: '',
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        grid: { right: '5%', top: '5%', bottom: '3%', width: '20%' },
        toolbox: {
          iconStyle: { normal: { borderColor: '#0d0e0e' } },
          top: 15,
          right: 35,
        },
        geo: {
          map: this.parentInfo.length === 1 ? 'china' : 'map',
          zoom: 1.1,
          roam: true,
          left: '5%',
          top: '10%',
          width: '45%',
          label: {
            normal: {
              show: true,
              color: 'rgb(249, 249, 249)',
              formatter: (p) => {
                switch (p.name) {
                  case '内蒙古自治区':
                    return '内蒙古';
                  case '西藏自治区':
                    return '西藏';
                  case '新疆维吾尔自治区':
                    return '新疆';
                  case '宁夏回族自治区':
                    return '宁夏';
                  case '广西壮族自治区':
                    return '广西';
                  case '香港特别行政区':
                    return '香港';
                  case '澳门特别行政区':
                    return '澳门';
                  default:
                    return p.name;
                }
              },
            },
            emphasis: { show: true, color: '#f75a00' },
          },
          itemStyle: {
            normal: {
              areaColor: '#24CFF4',
              borderColor: '#53D9FF',
              borderWidth: 1.3,
              shadowBlur: 15,
              shadowColor: 'rgb(58,115,192)',
              shadowOffsetX: 7,
              shadowOffsetY: 6,
            },
            emphasis: {
              areaColor: '#8dd7fc',
              borderWidth: 1.6,
              shadowBlur: 25,
            },
          },
        },
        visualMap: {
          min: min,
          max: max,
          left: '1%',
          bottom: '1%',
          calculable: true,
          seriesIndex: [0],
          inRange: { color: ['#24CFF4', '#2E98CA', '#1E62AC'] },
          textStyle: { color: '#24CFF4' },
        },
        xAxis: {
          type: 'value',
          scale: true,
          position: 'top',
          boundaryGap: false,
          splitLine: { show: false },
          axisLine: { show: true, lineStyle: { color: '#455B77' } },
          axisTick: { show: false },
          axisLabel: { margin: 2, textStyle: { color: '#2f2c2c' } },
        },
        yAxis: {
          type: 'category',
          nameGap: 16,
          axisLine: { show: true, lineStyle: { color: '#211e1e' } },
          axisTick: { show: false },
          axisLabel: { interval: 0, textStyle: { color: '#211e1e' } },
          data: xData,
        },
        series: [
          {
            name: '销售额度',
            type: 'map',
            geoIndex: 0,
            map: this.parentInfo.length === 1 ? 'china' : 'map',
            roam: true,
            zoom: 1.3,
            tooltip: {
              trigger: 'item',
              formatter: (p) => {
                let val = p.value;
                if (p.name === '南海诸岛') return;
                if (window.isNaN(val)) val = 0;
                return `<div style='text-align:left'>${p.name}:<br />销售额：${val.toFixed(2)}万</div>`;
              },
            },
            label: { normal: { show: false }, emphasis: { show: false } },
            data: mapData,
          },
          {
            name: '散点',
            type: 'effectScatter',
            coordinateSystem: 'geo',
            rippleEffect: { brushType: 'fill' },
            itemStyle: { normal: { color: '#F4E925', shadowBlur: 10, shadowColor: '#333' } },
            data: pointData,
            symbolSize: (val) => (val[2] === max ? 27 : 10),
            showEffectOn: 'render',
          },
          {
            type: 'bar',
            barGap: '-100%',
            barCategoryGap: '60%',
            itemStyle: { normal: { color: '#11AAFE' }, emphasis: { show: false } },
            data: yData,
          },
        ],
      };

      if (!this.myChart) {
        this.myChart = echarts.init(document.getElementById('chart-panel'));
      }
      this.myChart.setOption(option, true);

      this.myChart.off('click');
      this.myChart.on('click', this.echartsMapClick);
    },
    echartsMapClick(params) {
      if (!params.data) return;
      if (this.parentInfo[this.parentInfo.length - 1].code === params.data.cityCode) return;

      const data = params.data;
      this.parentInfo.push({ cityName: data.name, code: data.cityCode });
      this.init(data.cityCode);
    },
    handleBack() {
      if (this.parentInfo.length === 1) return;
      this.parentInfo.pop();
      this.init(this.parentInfo[this.parentInfo.length - 1].code);
    },
    resizeChart() {
      if (this.myChart) this.myChart.resize();
    },
  },
};
</script>

<style scoped>
.back {
  position: absolute;
  left: 25px;
  top: 25px;
  color: rgb(21, 21, 21);
  font-size: 16px;
  z-index: 100;
}
.map-container {
  width: 100%;
  height: 100%;
  position: relative;
  border:1px solid #ccc;
}
.map {
  width: 100%;
  height: 500px; /* 地图高度 */
  background-color: white;
}
</style>